// import url from 'url';
import * as fs from 'fs';
import * as path from 'path';
import axios from 'axios';
import * as cheerio from 'cheerio';
import { Injectable } from '@nestjs/common';
import { launchBrowser, mainTask, close } from '../utils/task';
import { sendToAi } from '../utils/cozeGpt';
// import { sendToAi } from '../utils/deepbricksGpt';

@Injectable()
export class XiaohongshuService {
  async startCrawler(reqUrl) {
    const data = await this.create(reqUrl);

    return {
      data: data,
    };
  }

  async create(reqUrl) {
    // 创建图片存放目录
    return new Promise((resolve, reject) => {
      axios
        .get(reqUrl)
        .then((response) => {
          if (response.status === 200) {
            const html = response.data;
            const $ = cheerio.load(html);

            // 标题 内容
            const title = $('#detail-title').text();
            const content = $('.note-text').text();

            // 获取所有cookies 并返回
            const allFiles = this.getAllFiles('./src/utils/cookies');
            const list = [];
            allFiles.forEach(async (file) => {
              const cookiesData = await fs.readFileSync(file);
              const cookies = JSON.parse(cookiesData.toString());
              const name = path.basename(file, '.json');

              // 图片
              const pics = [];
              $("meta[name='og:image']").each((index, element) => {
                // 网络位置
                const href = $(element).attr('content');

                // 保存到本地
                // const imagePath = `./hongshuUpload/${name}/${index}.jpg`;
                // this.downImgWidthUrl(href, imagePath);

                // 获取绝对路径
                // const absolutePath = path.resolve(imagePath);
                pics.push({
                  url: href,
                  // imagePath: imagePath,
                  // absolutePath: absolutePath,
                });
              });
              list.push({
                title,
                content,
                pics,
                user: {
                  name,
                  cookies,
                },
              });
            });
            resolve(list);
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  getAllFiles(dirPath, arrayOfFiles?) {
    const files = fs.readdirSync(dirPath);

    arrayOfFiles = arrayOfFiles || [];

    files.forEach(function (file) {
      if (fs.statSync(path.join(dirPath, file)).isDirectory()) {
        arrayOfFiles = this.getAllFiles(path.join(dirPath, file), arrayOfFiles);
      } else {
        arrayOfFiles.push(path.join(dirPath, file));
      }
    });

    return arrayOfFiles;
  }

  // 从url下载
  downImgWidthUrl(url, imagePath) {
    const folderPath = path.dirname(imagePath);

    fs.mkdir(folderPath, { recursive: true }, (err) => {
      if (err) {
        console.error(err);
        return;
      }

      axios({
        method: 'get',
        url: url,
        responseType: 'stream',
      }).then((response) => {
        response.data.pipe(fs.createWriteStream(imagePath));
      });
    });
  }

  // 本地上传
  uploadImgWidthLocal(file, name) {
    // 文件名
    const fileName = (file.originalname = Buffer.from(
      file.originalname,
      'latin1',
    ).toString('utf8'));

    return new Promise((resolve, reject) => {
      // 文件夹路径
      const folderPath = `./hongshuUpload/${name}`;
      fs.mkdir(folderPath, { recursive: true }, (err) => {
        if (err) {
          reject({
            data: err,
            code: -1,
          });
          return;
        }

        // 图片路径
        const imagePath = `${folderPath}/${fileName}`;
        fs.writeFile(imagePath, file.buffer, (err) => {
          if (err) {
            reject({
              data: err,
              code: -1,
            });
            return;
          }

          resolve({
            data: {
              url: imagePath,
              name: fileName,
            },
          });
        });
      });
    });
  }

  async pubLish(data) {
    const browser = await launchBrowser();

    // 接收小红书列表
    data.forEach(async (article, index) => {
      article.fileList.forEach(async (file, index2) => {
        // 下载远程图片
        if (file.url.indexOf('http') === 0) {
          const folderPath = `./hongshuUpload/${article.user.name}`;
          const fileName = path.basename(file.url);
          const imagePath = `${folderPath}/${fileName}.jpg`;
          this.downImgWidthUrl(file.url, imagePath);
          const absolutePath = path.resolve(imagePath);
          file.absolutePath = absolutePath;
        } else {
          // 处理手动上传的文件
          const absolutePath = path.resolve(file.url);
          file.absolutePath = absolutePath;
        }
      });

      await mainTask(browser, article);
    });
    // close(browser);
  }

  async chatWithAi(content) {
    return await sendToAi(content);
  }
}
